<?php
declare(strict_types=1);
namespace Hangpu888\Hpadmin\controller;

use FormBuilder\Factory\Elm;
use Hangpu888\Hpadmin\Controller;
use Hangpu888\Hpadmin\model\ConfigGroup;
use Hangpu888\Hpadmin\model\Webconfig;
use Hangpu888\Hpadmin\utils\builder\FormBuilder;
use Hangpu888\Hpadmin\utils\builder\ListBuilder;
use Hangpu888\Hpadmin\utils\Json;
use Hangpu888\Hpadmin\validate\Webconfig as ValidateWebconfig;

class Config extends Controller
{
    /**
     * 配置项表单
     *
     * @return void
     */
    public function index()
    {
        if (request()->method() == 'PUT') {
            $post = request()->post();
            foreach ($post as $name => $value) {
                $configModel = Webconfig::where('name', $name)->find();
                $configModel->value = $value;
                $configModel->save();
            }
            return Json::success('设置成功');
        } else {
            $dataTabs = $this->getTabs();
            $builder = new FormBuilder;
            $builder = $builder->initTabs($dataTabs['active']);
            $builder = $builder->setMethod('PUT');
            foreach ($dataTabs['tabs'] as $value) {
                $builder = $builder->addTab($value['title'], $value['name'], $value['children']);
            }
            $data = $builder->endTabs()->create();
            return Json::successRes($data);
        }
    }

    /**
     * 显示添加
     *
     * @return void
     */
    public function add()
    {
        try {
            $configModel            = new Webconfig;
            if (request()->method() == 'POST') {
                // 获取数据
                $cid                = request()->get('id');
                $post               = request()->post();
    
                //数据验证
                hpValidate(new ValidateWebconfig,$post);
    
                // 数据入库
                $post['cid']        = $cid;
                foreach ($post as $field => $value) {
                    $configModel->$field = $value;
                }
                if ($configModel->save()) {
                    return Json::success('添加成功');
                }else{
                    return Json::fail('添加失败');
                }
            }else{
                $builder = new FormBuilder;
                $data = $builder
                    ->setMethod('post')
                    ->addRow('title','input','配置名称','',[
                        'col'                               => [
                            'span'                          => 12
                        ]
                    ])
                    ->addRow('name','input','标签名称','',[
                        'col'                               => [
                            'span'                          => 12
                        ]
                    ])
                    ->addRow('value','input','默认数据','',[
                        'col'                               => [
                            'span'                          => 12,
                        ],
                    ])
                    ->addRow('placeholder','input','配置描述','',[
                        'col'                               => [
                            'span'                          => 12,
                        ],
                    ])
                    ->addRow('sort','input','配置排序','100',[
                        'col'                               => [
                            'span'                          => 12,
                        ],
                    ])
                    ->addRow('type','select','表单类型','',[
                        'options'                           => $configModel->getFormTypeOptions(),
                        'col'                               => [
                            'span'                          => 12
                        ],
                        'control'                           => [
                            [
                                'value'                     => ['select','radio','checkbox','switch'],
                                'where'                     => 'in',
                                'rule'                      => [
                                    [
                                        'type'              => 'input',
                                        'title'             => '选项数据',
                                        'field'             => 'extra',
                                        'value'             => '',
                                        'col'               => [
                                            'span'          => 12,
                                        ],
                                        'props'             => [
                                            'type'          => 'textarea',
                                            'placeholder'   => '请输入额外选项数据',
                                        ],
                                    ],
                                ],
                            ],
                        ]
                    ])
                    ->create();
                return Json::successRes($data);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 显示编辑
     *
     * @return void
     */
    public function edit()
    {
        try {
            $id = request()->get('id');
            $configModel        = Webconfig::where(['id'=> $id])->find();
            if (request()->method() == 'PUT') {
                // 数据获取
                $id                 = request()->get('id');
                $post               = request()->post();
    
                // 数据验证
                hpValidate(new ValidateWebconfig,$post);
    
                // 数据入库
                foreach ($post as $field => $value) {
                    $configModel->$field = $value;
                }
                if ($configModel->save()) {
                    return Json::success('修改成功');
                }else{
                    return Json::fail('修改失败');
                }
            }else{
                $data = $configModel->toArray();
                $builder = new FormBuilder;
                $form = $builder
                    ->setMethod('put')
                    ->addRow('title','input','配置名称','',[
                        'col'                               => [
                            'span'                          => 12
                        ]
                    ])
                    ->addRow('name','input','标签名称','',[
                        'disabled'                          => true,
                        'col'                               => [
                            'span'                          => 12
                        ]
                    ])
                    ->addRow('value','input','默认数据','',[
                        'col'                               => [
                            'span'                          => 12,
                        ],
                    ])
                    ->addRow('placeholder','input','配置描述','',[
                        'col'                               => [
                            'span'                          => 12,
                        ],
                    ])
                    ->addRow('sort','input','配置排序','100',[
                        'col'                               => [
                            'span'                          => 12,
                        ],
                    ])
                    ->addRow('type','select','表单类型','',[
                        'options'                           => $configModel->getFormTypeOptions(),
                        'col'                               => [
                            'span'                          => 12
                        ],
                        'control'                           => [
                            [
                                'value'                     => ['select','radio','checkbox','switch'],
                                'where'                     => 'in',
                                'rule'                      => [
                                    [
                                        'type'              => 'input',
                                        'title'             => '选项数据',
                                        'field'             => 'extra',
                                        'value'             => '',
                                        'col'               => [
                                            'span'          => 12
                                        ],
                                        'props'             => [
                                            'type'          => 'textarea',
                                            'placeholder'   => '请输入额外选项数据',
                                        ],
                                    ],
                                ],
                            ],
                        ]
                    ])
                    ->setFormData($data)
                    ->create();
                return Json::successRes($form);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 删除配置
     *
     * @return void
     */
    public function del()
    {
        $id = request()->get('id');
        $configModel = Webconfig::where(['id'=> $id])->find();
        if (!$configModel) {
            return Json::fail('找不到该数据');
        }
        if ($configModel->delete()) {
            return Json::success('删除成功');
        }else{
            return Json::fail('删除失败');
        }
    }

    /**
     * 显示配置项列表
     *
     * @return void
     */
    public function configlist()
    {
        $cid                        = request()->get('id');
        $list                       = Webconfig::where(['cid' => $cid])->paginate()->toArray();
        $builder                    = new ListBuilder;
        $data                       = $builder
            ->addColumn('rightButtonList', '操作', [
                'type' => 'template',
                'template' => 'rightButtonList',
                'width'             => '230',
            ])
            ->addTopButton('add', '添加', [
                'api'               => "/hpadmin/Config/add?cid={$cid}",
                'method'            => 'get',
                'title'             => '添加配置项'
            ])
            ->addRightButton('edit', '编辑', [
                'api'               => "/hpadmin/Config/edit",
                'method'            => 'get',
                'title'             => '修改配置项',
            ])
            ->addRightButton('delete', '删除', [
                'api'               => '/hpadmin/Config/del',
                'method'            => 'delete',
                'title'             => '确认要删除该数据吗？',
                'type'              => 'confirm',
                'content'           => '删除该数据不可恢复',
            ])
            ->addColumn('ctime', '创建时间')
            ->addColumn('title', '配置项名称')
            ->addColumn('name', '配置标签')
            ->addColumn('type', '表单类型')
            ->setData($list['data'])
            ->setDataPage($list['total'], $list['per_page'], $list['current_page'])
            ->create();
        return Json::successRes($data);
    }

    /**
     * 获取配置分组
     *
     * @return array
     */
    private function getTabs(): array
    {
        $list = ConfigGroup::distinct()->select()->toArray();
        $tabs = [];
        foreach ($list as $key => $value) {
            $tabs[$key]                 = [
                'title'                 => $value['title'],
                'name'                  => $value['name'],
                'icon'                  => $value['icon'],
            ];
            $tabs[$key]['children']     = $this->getConfig($value['id']);
        }
        $active                         = 0;
        $data['active']                 = $list[$active]['name'];
        $data['tabs']                   = $tabs;
        return $data;
    }

    /**
     * 获取系统配置
     *
     * @param [type] $cid
     * @return array
     */
    private function getConfig($cid): array
    {
        $map['cid'] = $cid;
        $list = Webconfig::where($map)->select()->toArray();
        $config = [];
        foreach ($list as $key => $value) {
            $type = $value['type'];
            $componentValue = $type == 'checkbox' ? [$value['value']] : $value['value'];
            $component = Elm::$type($value['name'], $value['title'], $componentValue);
            // 左侧文字提示
            if ($value['placeholder']) {
                $component = $component->info($value['placeholder']);
            }
            // 额外选项数据
            if ($value['extra'] && in_array($type, ['select', 'radio', 'checkbox'])) {
                $extras = explode('|', $value['extra']);
                $options = [];
                foreach ($extras as $key2 => $value2) {
                    list($optionValue, $label) = explode(',', $value2);
                    $options[$key2]['label']        = $label;
                    $options[$key2]['value']        = $optionValue;
                }
                $component->options($options);
            }
            $config[$key] = $component;
        }
        return $config;
    }
}